_Pragma("once");

#include <list>
#include <filesystem>

#include "LoopControlInfo.h"
#include "DateTimeUtility.h"
#include "SingletonTemplate.h"
#include "common.h"

#include "Log.h"

using LoopControlInfoList = std::list<LoopControlInfoPtr>;

class LoopControlInfoManager {
public:
    friend class SingletonTemplate<LoopControlInfoManager>;

    /** Default destructor */
    ~LoopControlInfoManager();

    bool load(const DateTimeUtility::ClockTime_t& timeOfDay);
    bool load(const DateTimeUtility::ClockTime_t& timeOfDay, const bool loadPrevInfoOfDay, LoopControlInfoList& loopControlInfos);

    static bool save(const DateTimeUtility::ClockTime_t& timeOfDay, LoopControlInfoList& loopControlInfos);
    static bool save(const std::string& timeOfDay, LoopControlInfoList& loopControlInfos);

    LoopControlInfoPtr locateLoopControlInfo(const DateTimeUtility::ClockTime_t& time, const int32_t offset);


    bool clear();

    bool remove() {
        clear();

        LOG_DEDUG("remove offline command files");
        std::filesystem::directory_iterator end;
        for (std::filesystem::directory_iterator fileIterator(OFFLINE_COMMAND_CONFIG); fileIterator != end; ++fileIterator){
            std::filesystem::remove(*fileIterator);
        }

        return true;
    }


    LoopControlInfoList& getLoopControlInfos(const DateTimeUtility::ClockTime_t& timeOfDay){
        if (mloopControlInfos.empty() || !sameYearMonth(timeOfDay)){
            load(timeOfDay);
        }

        return mloopControlInfos;
    }



    bool sameYearMonth(const DateTimeUtility::ClockTime_t& timeOfDay){
        std::string tempYearMonth;
        std::time_t time = DateTimeUtility::toTime_t(timeOfDay);
        std::tm dateTime = DateTimeUtility::toTm(time);
        DateTimeUtility::toYearMouthString(dateTime, tempYearMonth);

        return tempYearMonth == myearMonthString;
    }

    LoopControlInfoList& getLoopControlInfos(){
        return mloopControlInfos;
    }


protected:
    /** Default constructor */
    LoopControlInfoManager();

    LoopControlInfoList mloopControlInfos;

    std::filesystem::path mpath;

    std::string myearMonthString;

    bool mmodified; //!< Member variable "modified"
};


using LoopControlInfoManagerSingleton = SingletonTemplate<LoopControlInfoManager>;



